﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using KL.UFrame.Core.Exception;
using KL.UFrame.Core.Unity;

namespace KL.UFrame.Api
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected WebApiApplication()
        {
            this.Error += WebApiApplication_Error;
            this.BeginRequest += WebApiApplication_BeginRequest;
        }
       

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            UnityBootstrapper.Current.RegisterComponents();
        }

        /// <summary>
        /// 全局异常处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebApiApplication_Error(object sender, EventArgs e)
        {
            ApplicationError.Log(Server, Request, Response, User);
        }

        /// <summary>
        /// 处理跨域请求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebApiApplication_BeginRequest(object sender, EventArgs e)
        {
            var method = Request.HttpMethod.ToUpper();
            switch (method)
            {
                case "OPTIONS":
                    Response.Headers.Set("Access-Control-Max-Age", "1728000"); //20 days
                    Response.StatusCode = 200;
                    Response.End();
                    break;
            }
        }
    }
}
